var express = require('express');
var router = express.Router();
var multiparty = require('multiparty');
const OpenAI = require("openai");


const { listModel, qjxtijianModel, qjxguahaoModel, qjxcateModel, qjxcateesModel, qjxwenzhenModel, qjxfuModel,qjxshenModel,qjxzouModel,qjxyangModel,addressModel } = require('../model/model')

//陈晓凡
const AlipayFormData = require('alipay-sdk/lib/form').default
const alipaySdk = require('./alipay')
router.post("/pcpay", async (req, res) => {
  let { data } = req.body
  console.log(data);
  
  console.log()
  const formData = new AlipayFormData()
  formData.setMethod('get'); 
  // 通过addField增加参数
  // 在用户支付完成之后，支付宝服务器会根据传入的notify_url,以post请求的形式将支付结果作为参数通知到商户系统
  // 支付成功或失败都返回
  formData.addField('returnUrl', "http://www.baidu.com");//支付成功后返回的页面
  formData.addField('bizContent', {
    out_trade_no: data.money.out_trade_no,//订单号 64个字符以内 可包含字母、数字、下划线、且不能重复
    product_code: "FAST_INSTANT_TRADE_PAY",//销售产品码，与支付宝签约的产品码名称，仅支持FAST_INSTANT_TRADE_PAY
    total_amount: 123,// 订单总金额
    subject: '1221',// 订单描述
    body: '34234',// 商品描述
  })
  // 返回promise
  const result = await alipaySdk.exec(
    'alipay.trade.wap.pay',//统一收单下单并支付页面接口,
    {},//api请求的参数（包含 “公共请求参数”和“业务参数”）
    { formData: formData }// result为可以跳转支付链接的url
  )
  // res.json({ url: result })
  res.send({
    code: 200,
    result
  })
})
router.get('/chen_getlist', async (req, res, next) => {
  const list = await listModel.find()
  res.send({
    code: 200,
    data: list
  })
});

router.get('/chen_getlists', async (req, res, next) => {
  const { name } = req.query
  const query = {}
  if (name) {
    query.name = new RegExp(name, 'i')
  }
  const list = await listModel.find(query)
  res.send({
    code: 200,
    data: list
  })
});
// 这里也可以自定义角色
const systemMessages = [
  {
    role: "system",
    content: "你是 Kimi，由 Moonshot AI 提供的人工智能助手，你更擅长中文和英文的对话。你会为用户提供安全，有帮助，准确的回答。同时，你会拒绝一切涉及恐怖主义，种族歧视，黄色暴力等问题的回答。Moonshot AI 为专有名词，不可翻译成其他语言。",
  },
];
let messages = [];
async function makeMessages(input, n = 20) {
  messages.push({
    role: "user",
    content: input,
  });
  let newMessages = systemMessages;
  if (messages.length > 50) {
    messages = messages.slice(-50);
  }
  newMessages = newMessages.concat(messages);
  return newMessages;
}
async function chat(input) {
  try {
    const completion = await client.chat.completions.create({
      model: "moonshot-v1-8k",// 指定使用的语言模型
      messages: await makeMessages(input),
      temperature: 0.3// 控制输出的随机性程度，值越低输出越确定
    });
    const assistantMessage = completion.choices[0].message;
    messages.push(assistantMessage);
    return assistantMessage.content;
  } catch (error) {
    console.error("Error during chat completion:", error);
    throw error;
  }
}
router.post('/chat', async (req, res, next) => {
  try {
    const userInput = req.body.userInput;
    if (!userInput) {
      return res.status(400).send({
        code: 400,
        message: "请提供输入信息",
      });
    }
    const reply = await chat(userInput)
    res.send({
      code: 200,
      data: reply
    });
  } catch (error) {
    next(error);
  }
});

router.post('/upload', async (req, res, next) => {
  let form = new multiparty.Form()
  form.uploadDir = './upload'
  form.parse(req, (err, formdate, data) => {
    // console.log(data[].originalFilename);
    res.send({
      code: 200,
      path: 'http://127.0.0.1:3000/' + data.file[0].path
    })
  })
});

//秦久翔
router.get('/qjx_tijian', async (req, res, next) => {
  const qjxtijian = await qjxtijianModel.find()
  res.send({
    code: 200,
    data: qjxtijian
  })
})
router.get('/qjx_guahao', async (req, res, next) => {
  let { cate } = req.query
  console.log(cate);
  let lists = [{}]
  if (cate) {
    lists.push({ cate: cate })
  }
  const qjxwenzhen = await qjxwenzhenModel.find({ $and: lists }).populate('cate')
  console.log(qjxwenzhen);

  res.send({
    code: 200,
    data: qjxwenzhen
  })
})
router.get('/qjx_cates', async (req, res, next) => {
  const qjxcate = await qjxcateesModel.find()
  const qjxguahao = await qjxguahaoModel.find({ $and: lists }).populate('cate')
  console.log(qjxguahao);

  res.send({
    code: 200,
    data: qjxguahao
  })
})
router.get('/qjx_cate', async (req, res, next) => {
  const qjxcate = await qjxcateModel.find()
  res.send({
    code: 200,
    data: qjxcate
  })
})
//俯卧撑目标
router.get('/qjx_fus', async (req, res, next) => {
  const qjxfu = await qjxfuModel.find()
  res.send({
    code: 200,
    data: qjxfu
  })
})
router.post('/qjx_fus_add', async (req, res) => {
  let data = req.body
  console.log(data);
  await qjxfuModel.create(data)
  res.send({
    code: 200,
    msg: 'ok'
  })
})
//深蹲目标
router.get('/qjx_shens', async (req, res, next) => {
  const qjxshen = await qjxshenModel.find()
  res.send({
    code: 200,
    data: qjxshen
  })
})
router.post('/qjx_shens_add', async (req, res) => {
  let data = req.body
  console.log(data);
  await qjxshenModel.create(data)
  res.send({
    code: 200,
    msg: 'ok'
  })
})
//仰卧起坐目标
router.get('/qjx_yangs', async (req, res, next) => {
  const qjxyang = await qjxyangModel.find()
  res.send({
    code: 200,
    data: qjxyang
  })
})
router.post('/qjx_yangs_add', async (req, res) => {
  let data = req.body
  console.log(data);
  await qjxyangModel.create(data)
  res.send({
    code: 200,
    msg: 'ok'
  })
})
//步数目标
router.get('/qjx_zous', async (req, res, next) => {
  const qjxzou = await qjxzouModel.find()
  res.send({
    code: 200,
    data: qjxzou
  })
})
router.post('/qjx_zous_add', async (req, res) => {
  let data = req.body
  console.log(data);
  await qjxzouModel.create(data)
  res.send({
    code: 200,
    msg: 'ok'
  })
})
//地址管理
router.get('/address', async (req, res, next) => {
  const address = await addressModel.find()
  res.send({
    code: 200,
    data: address
  })
})
router.post('/address_add', async (req, res) => {
  let data = req.body
  console.log(data);
  await addressModel.create(data)
  res.send({
    code: 200,
    msg: 'ok'
  }) 
})
module.exports = router;
